package com.cmy.lesson03;

import com.cmy.lesson2.utils.JdbcUtils;

import java.sql.*;

/**
 * @Author Void
 * @Description //TODO 测试prepareStatement sql注入
 * @Date 13:50 2021/3/10
 * @Param
 * @return
 **/
public class SqlInjection {
    public static void main(String[] args) {
//        login("zhansan","123456");
        login("'' or 1=1 ","'' or 1=1 ");//无效
        //原因是,prepareStatement将所有传入的参数转为字符,若其中存在转义字符,直接忽略:比如`会被直接转义

    }

    public static void login(String username,String password) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            //select * from `users` where `NAME` = ''or '1=1' AND `PASSWORD` = ''or '1=1'(拼接后查出全部)
            String sql = "select * from `users` where `NAME` = ? AND `PASSWORD` = ?";
            pst = conn.prepareStatement(sql);
            pst.setString(1,username);
            pst.setString(2,password);

            rs = pst.executeQuery();
            while(rs.next()){
                System.out.println("name = "+rs.getString("NAME"));
                System.out.println("password = "+rs.getString("PASSWORD"));
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtils.release(conn,pst,rs);
        }
    }
}

    